const defaults = {
    timeout: 0
}

class InterceptorManager {
    constructor() {
        this.handlers = [];
        this.idCounter = 0; // 用于生成拦截器唯一ID
    }

    // 添加拦截器，返回唯一ID
    use(fulfilled, rejected) {
        const id = this.idCounter++;
        this.handlers.push({
            fulfilled,
            rejected,
            id
        });
        return id;
    }

    // 根据ID移除拦截器
    eject(id) {
        this.handlers = this.handlers.filter(handler => handler.id !== id);
    }
}

class Axios {
    constructor(instanceConfig = {}) {
        this.defaults = instanceConfig;
        this.interceptors = {
            request: new InterceptorManager(),
            response: new InterceptorManager()
        }
    }

    request(configOrUrl = {}, config = {}) {
        // 处理请求配置合并、URL拼接、请求头设置等逻辑（原逻辑不变）
        if (typeof configOrUrl === "string") {
            config.url = configOrUrl;
        } else {
            config = configOrUrl;
        }

        config = { ...this.defaults, ...config };
        config.method = (config.method || "get").toLowerCase();

        const { headers = {} } = config;
        if (config.baseURL && !config.url.startsWith("http://")) {
            config.url = config.baseURL + config.url;
        }

        if (config.params) {
            config.url = config.url + "?" + Object.keys(config.params).map(key => `${key}=${config.params[key]}`).join("&");
        }

        // 发送AJAX请求的核心逻辑（原逻辑不变）
        const _dispatchRequest = (config) => {
            return new Promise((resolve, reject) => {
                const request = new XMLHttpRequest();
                if (config.cancelToken) {
                    config.cancelToken.cancel.then(() => request.abort());
                }

                request.responseType = "json";
                request.timeout = config.timeout;
                request.open(config.method, config.url);

                for (let key in headers) {
                    request.setRequestHeader(key, headers[key]);
                }

                if (config.data) {
                    if (typeof config.data === "object") {
                        request.setRequestHeader("Content-Type", "application/json");
                        config.data = JSON.stringify(config.data);
                    } else {
                        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    }
                }

                request.send(config.data);

                request.onload = () => {
                    if (request.status >= 200 && request.status < 300) {
                        resolve({
                            config,
                            data: request.response,
                            headers: request.getAllResponseHeaders(),
                            request,
                            status: request.status,
                            statusText: request.statusText
                        });
                    } else {
                        reject({
                            code: "my-ERR_BAD_REQUEST",
                            config,
                            request,
                            status: request.status
                        });
                    }
                };

                request.ontimeout = () => {
                    reject({
                        code: "ECONNABORTED",
                        config,
                        message: `timeout of ${config.timeout}ms exceeded`,
                        name: "AxiosError",
                        request
                    });
                };

                request.onerror = () => reject({ code: "ERR_NETWORK" });
                request.onabort = () => reject({
                    code: "ERR_CANCELED",
                    message: "canceled",
                    name: "CanceledError"
                });
            });
        };

        // 构建拦截器执行链（原逻辑不变）
        const chain = [_dispatchRequest, undefined];
        this.interceptors.request.handlers.forEach(item => {
            chain.unshift(item.fulfilled, item.rejected);
        });
        this.interceptors.response.handlers.forEach(item => {
            chain.push(item.fulfilled, item.rejected);
        });

        let promise = Promise.resolve(config);
        while (chain.length) {
            promise = promise.then(chain.shift(), chain.shift());
        }
        return promise;
    }
}

function createInstance(defaultConfig) {
    const context = new Axios(defaultConfig);
    const instance = Axios.prototype.request.bind(context);
    for (let key in context) {
        instance[key] = context[key];
    }
    return instance;
}

const axios = createInstance(defaults);
axios.CancelToken = function (cb) {
    this.cancel = new Promise(resolve => cb(resolve));
}
axios.isCancel = function (info) {
    return info.code === "ERR_CANCELED";
}

export default axios;